/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.zn.mygateway.plugin.proxy;

import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.zn.mygateway.plugin.common.constant.Constants;
import org.zn.mygateway.plugin.plugin.MyPlugin;
import org.zn.mygateway.plugin.plugin.MyPluginChain;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * this is springCloud proxy impl.
 */
@Component
public class SpringCloudPlugin implements MyPlugin {//extends AbstractShenyuPlugin {

//    private final ShenyuSpringCloudServiceChooser serviceChooser;

    /**
     * Instantiates a new Spring cloud plugin.
     *
//     * @param serviceInstanceChooser the load balancer
     */
    public SpringCloudPlugin() {
        System.out.println("====================SpringCloudPlugin.SpringCloudPlugin is executing...");
//        this.serviceChooser = serviceInstanceChooser;
    }

//    @Override
//    protected String getRawPath(final ServerWebExchange exchange) {
//        return RequestUrlUtils.getRewrittenRawPath(exchange);
//    }

//    @Override
    protected Mono<Void> doExecute(final ServerWebExchange exchange, final MyPluginChain chain) {

        System.out.println("springCloud plugin doExecute start...");
//        if (Objects.isNull(rule)) {
//            return Mono.empty();
//        }
//        final ShenyuContext shenyuContext = exchange.getAttribute(Constants.CONTEXT);
//        assert shenyuContext != null;
//        final SpringCloudSelectorHandle springCloudSelectorHandle = SpringCloudPluginDataHandler.SELECTOR_CACHED.get().obtainHandle(selector.getId());
//        final SpringCloudRuleHandle ruleHandle = buildRuleHandle(rule);
//        String serviceId = springCloudSelectorHandle.getServiceId();
//        if (StringUtils.isBlank(serviceId)) {
//            Object error = ShenyuResultWrap.error(exchange, ShenyuResultEnum.CANNOT_CONFIG_SPRINGCLOUD_SERVICEID);
//            return WebFluxResultUtils.result(exchange, error);
//        }
        final String ip = "localhost";//Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getAddress().getHostAddress();
//        final Upstream upstream = serviceChooser.choose(serviceId, selector.getId(), ip, ruleHandle.getLoadBalance());
//        if (Objects.isNull(upstream)) {
//            Object error = ShenyuResultWrap.error(exchange, ShenyuResultEnum.SPRINGCLOUD_SERVICEID_IS_ERROR);
//            return WebFluxResultUtils.result(exchange, error);
//        }
        final String domain = "http://" + ip + ":8884";// upstream.buildDomain();
        setDomain(URI.create(domain + "/test/findByUserId?userId=test3"), exchange);
        //set time out.
        exchange.getAttributes().put(Constants.HTTP_TIME_OUT, Constants.TIME_OUT);
        return chain.execute(exchange);
    }

//    @Override
//    public Mono<Void> execute(ServerWebExchange exchange, MyPluginChain chain) {
//        return null;
//    }
//
    @Override
    public int getOrder() {
//        return PluginEnum.SPRING_CLOUD.getCode();
        return 200;
    }

    @Override
    public String named() {
//        return PluginEnum.SPRING_CLOUD.getName();
        return "springCloud";
    }

    /**
     * plugin is execute.
     *
     * @param exchange the current server exchange
     * @return default false.
     */
//    @Override
//    public boolean skip(final ServerWebExchange exchange) {
//        return skipExcept(exchange, RpcTypeEnum.SPRING_CLOUD);
//    }
//
//    @Override
//    protected Mono<Void> handleSelectorIfNull(final String pluginName, final ServerWebExchange exchange, final ShenyuPluginChain chain) {
//        return WebFluxResultUtils.noSelectorResult(pluginName, exchange);
//    }
//
//    @Override
//    protected Mono<Void> handleRuleIfNull(final String pluginName, final ServerWebExchange exchange, final ShenyuPluginChain chain) {
//        return WebFluxResultUtils.noRuleResult(pluginName, exchange);
//    }
//
//    private SpringCloudRuleHandle buildRuleHandle(final RuleData rule) {
//        return SpringCloudPluginDataHandler.RULE_CACHED.get().obtainHandle(CacheKeyUtils.INST.getKey(rule));
//    }

    private void setDomain(final URI uri, final ServerWebExchange exchange) {
        String domain = uri.getScheme() + "://" + uri.getAuthority();
        exchange.getAttributes().put("httpDomain", domain);
    }

    @Override
    public Mono<Void> execute(ServerWebExchange exchange, MyPluginChain chain) {
//                initCacheConfig();
//        final String pluginName = named();
//        PluginData pluginData = BaseDataCache.getInstance().obtainPluginData(pluginName);
//        // early exit
//        if (Objects.isNull(pluginData) || !pluginData.getEnabled()) {
//            return chain.execute(exchange);
//        }
//        final String path = getRawPath(exchange);
//        List<SelectorData> selectors = BaseDataCache.getInstance().obtainSelectorData(pluginName);
//        if (CollectionUtils.isEmpty(selectors)) {
//            return handleSelectorIfNull(pluginName, exchange, chain);
//        }
//        SelectorData selectorData = obtainSelectorDataCacheIfEnabled(path);
//        // handle Selector
//        if (Objects.nonNull(selectorData) && StringUtils.isBlank(selectorData.getId())) {
//            return handleSelectorIfNull(pluginName, exchange, chain);
//        }
//        if (Objects.isNull(selectorData)) {
//            selectorData = trieMatchSelector(exchange, pluginName, path);
//            if (Objects.isNull(selectorData)) {
//                selectorData = defaultMatchSelector(exchange, selectors, path);
//                if (Objects.isNull(selectorData)) {
//                    return handleSelectorIfNull(pluginName, exchange, chain);
//                }
//            }
//        }
//        printLog(selectorData, pluginName);
//        if (!selectorData.getContinued()) {
//            // if continued， not match rules
//            return doExecute(exchange, chain, selectorData, defaultRuleData(selectorData));
//        }
//        List<RuleData> rules = BaseDataCache.getInstance().obtainRuleData(selectorData.getId());
//        if (CollectionUtils.isEmpty(rules)) {
//            return handleRuleIfNull(pluginName, exchange, chain);
//        }
//        if (selectorData.getType() == SelectorTypeEnum.FULL_FLOW.getCode()) {
//            //get last
//            RuleData rule = rules.get(rules.size() - 1);
//            printLog(rule, pluginName);
//            return doExecute(exchange, chain, selectorData, rule);
//        }
//        // lru map as L1 cache,the cache is enabled by default.
//        // if the L1 cache fails to hit, using L2 cache based on trie cache.
//        // if the L2 cache fails to hit, execute default strategy.
//        RuleData ruleData = obtainRuleDataCacheIfEnabled(path);
//        if (Objects.nonNull(ruleData) && Objects.isNull(ruleData.getId())) {
//            return handleRuleIfNull(pluginName, exchange, chain);
//        }
//        if (Objects.isNull(ruleData)) {
//            // L1 cache not exist data, try to get data through trie cache
//            ruleData = trieMatchRule(exchange, selectorData, path);
//            // trie cache fails to hit, execute default strategy
//            if (Objects.isNull(ruleData)) {
//                ruleData = defaultMatchRule(exchange, rules, path);
//                if (Objects.isNull(ruleData)) {
//                    return handleRuleIfNull(pluginName, exchange, chain);
//                }
//            }
//        }
//        printLog(ruleData, pluginName);
        System.out.println("++++++++++++++++++++++++SpringCloudPlugin.execute is executing...");
        return doExecute(exchange, chain);
    }
}
